package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.constant.CrowdContant;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectConsumerHandler {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    /**
     * 获取项目详情
     * @param projectId
     * @param model
     * @return
     */
    @RequestMapping("/get/project/detail/{projectId}")
    public String getProjectDetail(
            @PathVariable("projectId") Integer projectId, Model model
    ) {
        ResultEntity<DetailProjectVO> remoteServiceDetailProjectVORemote = mySQLRemoteService.getDetailProjectVORemote(projectId);

        String result = remoteServiceDetailProjectVORemote.getResult();
        if (ResultEntity.SUCCESS.equals(result)){
            DetailProjectVO detailProjectVO = remoteServiceDetailProjectVORemote.getData();

            model.addAttribute("detailProjectVO",detailProjectVO);
        }

        return "project-detail";
    }
    /**
     * 2 收集表单数据执行保存
     * @param modelMap
     * @param session
     * @param memberConfirmInfoVO
     * @return
     */
    @RequestMapping("/create/confirm")
    public String saveConfirm(ModelMap modelMap, HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO) {

        // 1.从 Session 域读取之前临时存储的 ProjectVO 对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdContant.ATTR_NAME_TEMPLE_PROJECT);

        if (projectVO==null){
            throw new RuntimeException(CrowdContant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }
        // 3.将确认信息数据设置到 projectVO 对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 4.从 Session 域读取当前登录的用户
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdContant.ATTR_NAME_MEMBER);

        Integer memberId = memberLoginVO.getId();
        // 5.调用远程方法保存 projectVO 对象
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO, memberId);

        // 6.判断远程的保存操作是否成功
        String result = saveResultEntity.getResult();

        if (ResultEntity.FAILED.equals(result)){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE, saveResultEntity.getMessage());
            return "project-confirm";
        }

        // 7.将临时的 ProjectVO 对象从 Session 域移除
        session.removeAttribute(CrowdContant.ATTR_NAME_TEMPLE_PROJECT);
        // 8.如果远程保存成功则跳转到最终完成页面
         return "redirect:http://localhost/project/create/success";
    }
    /**
     * 接收整个回报信息数据
     */

    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session) {

        try {
            //从session域读取缓存的projectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdContant.ATTR_NAME_TEMPLE_PROJECT);

            // 2.判断 projectVO 是否为 null
             if(projectVO == null) {
             return ResultEntity.failed(CrowdContant.MESSAGE_TEMPLE_PROJECT_MISSING);
             }

             //获取存储回报信息的集合
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

             if (returnVOList==null || returnVOList.size()==0){
                 // 5.创建集合对象对 returnVOList 进行初始化
                  returnVOList = new ArrayList<>();
                 // 6.为了让以后能够正常使用这个集合，设置到 projectVO 对象中
                  projectVO.setReturnVOList(returnVOList);
             }
            // 7.将收集了表单数据的 returnVO 对象存入集合
            returnVOList.add(returnVO);
            // 8.把数据有变化的 ProjectVO 对象重新存入 Session 域，以确保新的数据最终能够 存入 Redis
            session.setAttribute(CrowdContant.ATTR_NAME_TEMPLE_PROJECT, projectVO);

            return ResultEntity.successWithoutData();
        }catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());

        }
    }

    /**
     * 接收页面异步上传的图片
     * @param returnPicture
     * @return
     * @throws IOException
     */
    @RequestMapping("/create/upload/return/picture.json")
    @ResponseBody
    public ResultEntity<String> uploadReturnPicture(// 接收用户上传的文件
                                                    @RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {

        //上传文件到OSS的参数

        String accessKeyId = ossProperties.getAccessKeyId();

        String accessKeySecret = ossProperties.getAccessKeySecret();

        String bucketDomain = ossProperties.getBucketDomain();

        String bucketName = ossProperties.getBucketName();

        String endPoint = ossProperties.getEndPoint();

        String originalName = ossProperties.getOriginalName();
        ResultEntity<String>  uploadReturnPicResultEntity = CrowdUtil.uploadFileToOss(endPoint, bucketName, accessKeyId, accessKeySecret, bucketDomain, returnPicture.getInputStream(), returnPicture.getOriginalFilename());

        System.out.println(uploadReturnPicResultEntity);

        return uploadReturnPicResultEntity;
    }
    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            // 接收除了上传图片之外的其他普通数据
            ProjectVO projectVO,
            //接收上传头像
            MultipartFile headerPicture,
            //接收上传详情的图片
            List<MultipartFile> detailPictureList,
            //用来将收集了一部分数据的 ProjectVO 对象存入 Session 域
            HttpSession session,
            // 用来在当前操作失败后返回上一个表单页面时携带提示消息
            ModelMap modelMap

    ) throws IOException {

        //完成头像上传
        boolean headerPictureEmpty = headerPicture.isEmpty();
        if (headerPictureEmpty){
            //没有上传头像，返回表单页面显示错误信息
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGEAGE_HEADER_PIC_EMPTY);

            return "project-launch";

        }
        //上传文件到OSS的参数

        String accessKeyId = ossProperties.getAccessKeyId();

        String accessKeySecret = ossProperties.getAccessKeySecret();

        String bucketDomain = ossProperties.getBucketDomain();

        String bucketName = ossProperties.getBucketName();

        String endPoint = ossProperties.getEndPoint();



        //上传了头像，执行上传
        ResultEntity<String> uploadHeaderPicResult =
                CrowdUtil.uploadFileToOss(endPoint, bucketName, accessKeyId, accessKeySecret, bucketDomain, headerPicture.getInputStream(), headerPicture.getOriginalFilename());

        String result = uploadHeaderPicResult.getResult();

        //判断头像是否上传成功
        if (ResultEntity.SUCCESS.equals(result)){
            //上传成功，从返回的数据获取图片的访问路径
            String headPicPath = uploadHeaderPicResult.getData();

            //存入到ProjectVO对象
            projectVO.setHeaderPicturePath(headPicPath);

        }else {
            //上传失败，返回表单显示错误信息
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        }

        //上传详情图片
        //创建存放详情图片路径的集合
        ArrayList<String> detailPicPathList = new ArrayList<>();

        //检查detailPictureList是否有效
        if (detailPictureList==null && detailPictureList.size()==0){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }

        //遍历detailPictureList集合
        for (MultipartFile detailPicture:detailPictureList){
            //.当前 detailPicture 是否为空
            if (detailPicture.isEmpty()){
                // 5.检测到详情图片中单个文件为空也是回去显示错误消息
                 modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE, CrowdContant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }

//            执行上传
            ResultEntity<String> uploadDetailPicResult = CrowdUtil.uploadFileToOss(endPoint, bucketName, accessKeyId, accessKeySecret, bucketDomain, detailPicture.getInputStream(), detailPicture.getOriginalFilename());

            // 7.检查上传结果
             String detailUploadResult = uploadDetailPicResult.getResult();
             if(ResultEntity.SUCCESS.equals(detailUploadResult)) {
                 String detailPicturePath = uploadDetailPicResult.getData();
                 // 8.收集刚刚上传的图片的访问路径
                  detailPicPathList.add(detailPicturePath);
             } else {
                 // 9.如果上传失败则返回到表单页面并显示错误消息
                  modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE, CrowdContant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);

                 return "project-launch";
             }
        }
        // 10.将存放了详情图片访问路径的集合存入 ProjectVO 中
         projectVO.setDetailPicturePathList(detailPicPathList);
        // 1.将 ProjectVO 对象存入 Session 域
         session.setAttribute(CrowdContant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
        // 2.以完整的访问路径前往下一个收集回报信息的页面
         return "redirect:http://localhost/project/return/info/page";

    }
}
